package initialize

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	_ "github.com/mbobakov/grpc-consul-resolver" // It's important
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"shop_api/global"
	"shop_api/proto"
)

// 负载均衡连接
func InitSrvConn() {
	config := api.DefaultConfig()

	config.Address = fmt.Sprintf("%s:%s", global.ServiceConfig.ConsulConfig.Host, global.ServiceConfig.ConsulConfig.Port)
	fmt.Println(global.ServiceConfig.ConsulConfig)
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}

	userSrvHost := ""
	userSrvPort := 0
	if err != nil {
		zap.S().Error("初始化consul信息错误", err.Error())
		return
	}
	services, err := client.Agent().ServicesWithFilter(fmt.Sprintf("Service==\"%s\"", global.ServiceConfig.UserSrvConfig.Name)) //获取consul注册的地址和端口

	for _, v := range services {
		fmt.Println(v.Port)
		userSrvHost = v.Address
		userSrvPort = v.Port
		break
	}
	if userSrvHost == "" || userSrvPort == 0 {
		zap.S().Error("consul信息错误")
		return
	}
	var opts []grpc.DialOption
	opt := append(opts, grpc.WithInsecure())
	opt = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	//opt = append(opts, grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`))

	servClient, err := grpc.NewClient(fmt.Sprintf("consul://%s:%d/user-srv?wait=14s&tag=user-srv", userSrvHost, 8500), opt...)
	if err != nil {
		zap.S().Error("客户端连接失败", err.Error())
		return
	}
	global.UserClient = proto.NewUserClient(servClient)
}

func InitSrvClient() {

	//从注册中心获取用户服务信息start
	config := api.DefaultConfig()

	config.Address = fmt.Sprintf("%s:%d", global.ServiceConfig.ConsulConfig.Host, global.ServiceConfig.ConsulConfig.Port)
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}

	userSrvHost := ""
	userSrvPort := 0
	if err != nil {
		zap.S().Error("初始化consul信息错误", err.Error())
		return
	}

	services, err := client.Agent().ServicesWithFilter(fmt.Sprintf("Service==\"%s\"", global.ServiceConfig.UserSrvConfig.Name)) //获取consul注册的地址和端口

	for _, v := range services {
		fmt.Println(v.Port)
		userSrvHost = v.Address
		userSrvPort = v.Port
		break
	}

	if userSrvHost == "" || userSrvPort == 0 {
		zap.S().Error("consul信息错误")
		return
	}
	//从注册中心获取用户服务信息end

	var opts []grpc.DialOption
	opt := append(opts, grpc.WithInsecure())
	opt = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))

	servClient, err := grpc.NewClient(fmt.Sprintf("%s:%d", userSrvHost, userSrvPort), opt...)

	if err != nil {
		zap.S().Error("客户端连接失败", err.Error())
		return
	}
	global.UserClient = proto.NewUserClient(servClient)
}
